<script setup lang="ts">
import { onMounted, provide, ref, reactive, type Ref } from 'vue'
import InjectChild from './InjectChild.vue'
import type { Item } from './util'
import { injectionKey } from './util'
import { nextKey } from '@/widgets/util'

const child = ref<InstanceType<typeof InjectChild>>()

const provided = ref('abc')
const item: Item = reactive({
  name: 'item-name',
  callback() {
    console.log('item called')
  }
})

provide(injectionKey, provided)

onMounted(() => {
  console.log('child', child.value)
  provided.value = 'Hello'
})

function callChildExposed() {
  child.value?.exposed11()
}

function changeItemName() {
  item.name = 'i: ' + nextKey()
}
</script>
<template>
  <div class="inject-demo">
    <div><span>provided</span> {{ provided }}</div>
    <div><button @click="callChildExposed">call child exposed</button></div>
    <div>
      <button @click="changeItemName">change item.name</button>
    </div>
    <hr />
    <InjectChild ref="child" id="inject-id" :item="item" />
  </div>
</template>
<style lang="scss">
.inject-demo {
  background-color: #fff;
  padding: 1em;
  width: 20em;
  > div {
    margin-bottom: 1em;
  }
  > hr {
    background-color: #000;
  }
}
</style>
